from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.tmt.v20180321 import tmt_client, models


class DeepSeekChatSession:
    def __init__(self):
        # 初始化会话历史
        self.conversation_history = []
        self.secret_id = 'AKIDjJhtujOp4D9rVw996qNgmgNr8C5oVDl6'
        self.secret_key = 'IaotlQs8B1hBSWP6bBOTL2ZvFNTM2Vdl'
        # 腾讯云认证
        self.cred = credential.Credential(self.secret_id, self.secret_key)

        # 客户端配置
        http_profile = HttpProfile()
        http_profile.endpoint = "tmt.tencentcloudapi.com"
        client_profile = ClientProfile()
        client_profile.httpProfile = http_profile
        self.client = tmt_client.TmtClient(self.cred, "ap-guangzhou", client_profile)

    def add_message(self, role, content):
        """添加对话历史"""
        self.conversation_history.append({"role": role, "content": content})

    def call_with_web_search(self, question, enable_web=True):
        """调用API并保持上下文"""
        # 1. 添加用户新问题到历史
        self.add_message("user", question)

        # 2. 构建历史对话上下文
        context = "\n".join(
            f"{msg['role']}: {msg['content']}"
            for msg in self.conversation_history[-6:]  # 限制历史长度避免过长
        )

        # 3. 准备API请求
        req = models.TextTranslateRequest()
        req.SourceText = context  # 传入完整上下文
        req.Source = "auto"
        req.Target = "zh"
        req.ProjectId = 0

        # 4. 联网配置（根据参数动态启用）
        if enable_web:
            req.Extra = {
                "EnableWebSearch": True,
                "SearchEngine": "sogou",
                "SearchDepth": 3,
                "ContextAwareSearch": True  # 关键：基于上下文优化搜索
            }

        # try:
        # 5. 调用API
        resp = self.client.TextTranslate(req)

        # 6. 处理响应
        if resp.Response.Error:
            return f"错误: {resp.Response.Error.Message}"

        answer = resp.Response.TargetText
        sources = resp.Response.Extra.get("SearchResults", [])

        # 7. 将AI回复加入历史
        self.add_message("assistant", answer)

        # 8. 格式化输出
        result = {"answer": answer}
        if enable_web:
            result["sources"] = [
                {
                    "title": s.get("Title", "无标题"),
                    "url": s.get("Url", ""),
                    "snippet": s.get("Snippet", "")[:100] + "..."
                }
                for s in sources[:2]  # 只显示前2个来源
            ]
        return result

        # except Exception as e:
        #     return f"API调用失败: {str(e)}"


# 使用示例
if __name__ == "__main__":
    # 初始化会话（替换为你的密钥）
    chat = DeepSeekChatSession()

    # 第一问（开启联网）
    print("用户: 2025年奥运会在哪里举办？")
    response = chat.call_with_web_search("2025年奥运会在哪里举办？")
    print("AI:", response)
    for src in response.get("sources", []):
        print(f"来源: {src['title']}\n链接: {src['url']}\n")

    # 第二问（延续上文，不重复联网）
    print("\n用户: 中国队哪些项目有夺金希望？")
    response = chat.call_with_web_search("中国队哪些项目有夺金希望？", enable_web=False)  # 复用之前检索结果
    print("AI:", response["answer"])

    # 第三问（强制刷新联网信息）
    print("\n用户: 现在奖牌榜最新情况如何？")
    response = chat.call_with_web_search("现在奖牌榜最新情况如何？", enable_web=True)  # 重新联网
    print("AI:", response["answer"])
    for src in response.get("sources", []):
        print(f"来源: {src['title']}\n链接: {src['url']}\n")